package com.may.wind.service;

import com.may.wind.dao.ArticleRepository;
import com.may.wind.entity.Article;
import com.may.wind.pojo.WindPage;
import com.may.wind.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class ArticleService {
    @Autowired
    ArticleRepository articleRepository;

    @Autowired
    RedisUtil redisUtil;

    public WindPage list(int page, int size) {
        WindPage<Article> articles;
        String key = "articlePage:" + page;
        Object articlePageCache = redisUtil.get(key);
        articles = (WindPage<Article>) articlePageCache;

        if (articles == null || articles.getContent().size() == 0) {
            Sort sort = Sort.by(Sort.Direction.DESC, "id");
            Page<Article> articlesInDb = articleRepository.findAll(PageRequest.of(page, size, sort));
            articles = new WindPage<>(articlesInDb);
            redisUtil.set(key, articles);
        }
        return articles;
    }

    public Article findById(int id) {
        Article article;
        String key = "article:" + id;
        Object articleCache = redisUtil.get(key);

        if (articleCache == null) {
            article = articleRepository.findById(id);
            redisUtil.set(key, article);
        } else {
            article = (Article) articleCache;
        }
        return article;
    }

    public void addOrUpdate(Article article) {
        articleRepository.save(article);

        redisUtil.delete("article" + article.getId());
        Set<String> keys = redisUtil.keys("articlePage*");
        redisUtil.delete(keys);
    }

    public void delete(long id) {
        articleRepository.deleteById(id);

        redisUtil.delete("article:" + id);
        Set<String> keys = redisUtil.keys("articlePage*");
        redisUtil.delete(keys);
    }
}
